package com.example.demo.controller;

import com.example.demo.Res.Res;
import com.example.demo.dto.UserLoginDto;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user/")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("login")
    @CrossOrigin
    public Res login(@RequestBody User user) {
        final UserLoginDto login = userService.login(user);
        if(login != null) {
            return Res.litOk("登录成功，前往首页", login);
        } else {
            return Res.litNo("登录失败请检查账号或者密码填写是否错误", null);
        }
    }

    @PostMapping("unLogin")
    @CrossOrigin
    public Res unLogin(@RequestParam String id) {
        final int i = userService.unLogin(id);
        if(i != 0) {
            return Res.litOk("退出登录成功", null);
        } else {
            return Res.litNo("退出登录失败服务器错误", null);
        }
    }
    @GetMapping("all")
    @CrossOrigin
    public Res all(@RequestParam String userName, @RequestParam String accountNumber) {
        final List<User> users = userService.selectAll(userName, accountNumber);
        if(users.size() != 0) {
            return Res.litOk("", users);
        } else {
            return Res.litNo("", users);
        }
    }

    @PostMapping("update")
    @CrossOrigin
    public Res update(@RequestBody User user) {
        final int i = userService.update(user);
        if(i != 0) {
            return Res.litOk("更新用户成功", null);
        } else {
            return Res.litNo("更新用户失败", null);
        }
    }

    @PostMapping("delete")
    @CrossOrigin
    public Res delete(@RequestParam int id) {
        System.out.println(123123);
        System.out.println(id);
        final int i = userService.delete(id);
        if(i != 0) {
            return Res.litOk("删除用户成功", null);
        } else {
            return Res.litNo("删除用户失败", null);
        }
    }

    @PostMapping("add")
    @CrossOrigin
    public Res add(@RequestBody User user) {
        final int i = userService.add(user);
        if(i != 0) {
            return Res.litOk("删除用户成功", null);
        } else {
            return Res.litNo("删除用户失败", null);
        }
    }
}
